var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var _limitMenu = system.MENULIMIT.BATCH01;
var _menuParam = config.OPTIONLIMIT;
var se_type = $("#se_type").val();
var queryurl = config.BASEPATH+'batch/sell/page';

var handle = {
	operate: function(oper, id){//修改、新增
		if(oper == 'add'){
			url = config.BASEPATH+"batch/sell/to_add/"+se_type;
			data = {oper: oper, callback:this.callback};
		}else if(oper == 'edit'){
			url = config.BASEPATH+"batch/sell/to_update?se_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'view'){
			url = config.BASEPATH+"batch/sell/to_view?se_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'approve'){
			url = config.BASEPATH+"batch/sell/to_view?se_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'stop'){
			url = config.BASEPATH+"batch/sell/to_view?se_id="+id;
			data = {oper: oper,callback: this.callback};
		}else{
			return false;
		}
		$.dialog({
			title : false,
			content : 'url:'+url,
			data: data,
			max : false,
			min : false,
			cache : false,
			lock: false
		}).max();
	},
	del: function(rowId){//删除
		var rowData = $("#grid").jqGrid("getRowData", rowId);
	 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'batch/sell/del',
				data:{"number":rowData.se_number},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : '删除成功!'});
						$('#grid').jqGrid('delRowData', rowId);
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		});	
    },
    callback: function(data, oper, dialogWin){
		if(oper == "edit") {
			THISPAGE.reloadData();
			dialogWin && dialogWin.api.close();
		}
		if(oper == "approve") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		}
		if(oper == "view") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		}
		if(oper == "add"){
			THISPAGE.reloadData();
			dialogWin && dialogWin.api.close();
		}
	},
	operFmatter : function(val, opt, row){
		var btnHtml = '';
		if (row.se_ar_state == '0') {
            btnHtml += '<input type="button" value="审核" class="btn_sp" onclick="javascript:handle.operate(\'approve\',' + opt.rowId + ');" />';
        }else if (row.se_ar_state == '2') {
            btnHtml += '<input type="button" value="修改" class="btn_xg" onclick="javascript:handle.operate(\'edit\',' + opt.rowId + ');" />';
        }else if (row.se_ar_state == '1') {//审核通过
        	btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
        } 
		btnHtml += '<input type="button" value="流程" class="btn_qh" onclick="javascript:listBillProcess(\''+row.se_number+'\',\'t_batch_sell\');" />';
		return btnHtml;
	},
	formatArState:function(val, opt, row){//0：未审核；1：已审核2：已退回
		if(val == 0){
			return '未审核';
		}else if(val == 1){
			return '已审核';
		}else if(val == 2){
			return '已退回';
		}
		return val;
	}
};
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		dateRedioClick("theDate");
		this.$_ar_state = $("#ar_state").cssRadio({ callback: function($_obj){
			$("#se_ar_state").val($_obj.find("input").val());
		}});
	},
	gridTotal:function(){
    	var grid=$('#grid');
		var se_amount=grid.getCol('se_amount',false,'sum');
		var se_money=grid.getCol('se_money',false,'sum');
    	var se_discount_money=grid.getCol('se_discount_money',false,'sum');
    	var se_rebatemoney=grid.getCol('se_rebatemoney',false,'sum');
    	var se_stream_money=grid.getCol('se_stream_money',false,'sum');
    	var se_receivable=grid.getCol('se_receivable',false,'sum');
    	var se_retailmoney=grid.getCol('se_retailmoney',false,'sum');
    	var userData = $("#grid").getGridParam('userData');
    	grid.footerData('set',{se_number:'本页小计<br>总计',
    		se_amount:se_amount+"<br>"+userData.se_amount,
    		se_money:se_money.toFixed(2)+"<br>"+userData.se_money.toFixed(2),
    		se_discount_money:se_discount_money.toFixed(2)+"<br>"+userData.se_discount_money.toFixed(2),
    		se_rebatemoney:se_rebatemoney.toFixed(2)+"<br>"+userData.se_rebatemoney.toFixed(2),
    		se_stream_money:se_stream_money.toFixed(2)+"<br>"+userData.se_stream_money.toFixed(2),
    		se_receivable:se_receivable.toFixed(2)+"<br>"+userData.se_receivable.toFixed(2),
    		se_retailmoney:se_retailmoney.toFixed(2)+"<br>"+userData.se_retailmoney.toFixed(2)});
    },
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
	    	{name: 'operate',label:'操作',width: 100, formatter: handle.operFmatter,align:'center', sortable:false},
	    	{name: 'se_number',label:'单据编号',index: 'se_number',width:140},
	    	{name: 'se_order_number',label:'订单编号',index: 'se_order_number',width:100},
	    	{name: 'client_name',label:'批发客户',index: 'client_name',width:120},
	    	{name: 'client_shop_name',label:'客户店铺',index: 'client_shop_name',width:120},
	    	{name: 'depot_name',label:(se_type == '0'?'发':'退')+'货仓库',index: 'depot_name',width:120},
	    	{name: 'se_manager',label:'经办人',index: 'se_manager',width:60},
	    	{name: 'se_amount',label:'数量',index: 'se_amount',width:50,align:'right'},
	    	{name: 'se_money',label:'批发金额',index: 'se_money',width:80,align:'right',formatter: PriceLimit.formatByBatch},
	    	{name: 'se_discount_money',label:'优惠金额',index: 'se_discount_money',width:60,align:'right',formatter: PriceLimit.formatMoney},
	    	{name: 'se_rebatemoney',label:'返点金额',index: 'se_rebatemoney',width:60,align:'right',formatter: PriceLimit.formatMoney},
	    	{name: 'se_stream_money',label:'物流金额',index: 'se_stream_money',width:60,align:'right',formatter: PriceLimit.formatMoney},
	    	{name: 'se_receivable',label:'应收金额',index: 'se_receivable',width:80,align:'right',formatter: PriceLimit.formatByBatch},
	    	{name: 'se_retailmoney',label:'零售金额',index: 'se_retailmoney',width:80,align:'right',formatter: PriceLimit.formatBySell},
	    	{name: 'se_ar_state',label:'审核状态',index: 'se_ar_state',width:60,formatter: handle.formatArState,hidden:$("#fromJsp").val() == "warn"},
	    	{name: 'se_ar_date',label:'审核日期',index: 'se_ar_date',width:80,hidden:$("#fromJsp").val() == "warn"},
	    	{name: 'se_make_date',label:'制单日期',index: 'se_make_date',width:80},
	    	{name: 'se_maker',label:'制单人',index: 'se_maker',width:60},
	    	{name: 'se_remark',label:'备注',index: 'se_remark',width:100}
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'json',
			width: gridWH.w-12,
			height: gridWH.h-90,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			userDataOnFooter: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
                userdata: 'data.data',
				repeatitems : false,
				id: 'se_id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.gridTotal();
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'se_type='+$("#se_type").val();
		params += '&se_isdraft=0';
		params += '&se_ar_state='+$("#se_ar_state").val();
		params += '&begindate='+$("#begindate").val();
		params += '&enddate='+$("#enddate").val();
		params += '&se_client_code='+$("#se_client_code").val();
		params += '&se_depot_code='+$("#se_depot_code").val();
		params += '&se_manager='+Public.encodeURI($("#se_manager").val());
		params += '&se_number='+Public.encodeURI($("#se_number").val());
		return params;
	},
	reset:function(){
		$("#se_client_code").val("");
		$("#se_depot_code").val("");
		$("#se_number").val("");
		$("#se_manager").val("");
		$("#client_name").val("");
		$("#depot_name").val("");
		THISPAGE.$_date.setValue(0);
		THISPAGE.$_ar_state.setValue(0);
		$("#begindate").val("");
		$("#enddate").val("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		//新增
		$('#btn-add').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.INSERT)) {
				return ;
			}
			handle.operate('add');
		});
		$('#btn-del').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var rowId = $('#grid').jqGrid('getGridParam','selrow');
			if(rowId == null || rowId == ''){
				Public.tips({type: 1, content : "您未选择任何数据"});
				return;
			}
			var rowData =$("#grid").jqGrid("getRowData", rowId);
			if(rowData.se_ar_state == "已审核"){
				Public.tips({type: 1, content : "单据已审核，不能删除"});
				return;
			}
			handle.del(rowId)
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		//导出
		$('#btn-export').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.EXPORT)) {
				return ;
			};
			window.open(config.BASEPATH+'batch/sell/report?' + THISPAGE.buildParams());
		});
	}
}
THISPAGE.init();